package ar.uba.fi.taller2.jh.BPtree;

import java.util.*;
import ar.uba.fi.taller2.jh.BPBasicTree.*;
import ar.uba.fi.taller2.jh.Tree.*;

/*****************************************************************************
 * @author Sebastian rivas
 * @version 1.0
 * 
 ****************************************************************************/

public class BPLeafNode extends BPBasicLeafNode {

  public BPLeafNode(Comparator comp, int n_recs, boolean _isRoot, Tree _tree) {
	super(comp,n_recs, _isRoot, _tree);
 }

  /****************************************************************************
   * CONSTRUCTOR
   *
   * @param o BPLeafNode
   ***************************************************************************/

  public BPLeafNode(BPLeafNode o) {
	super(o);
  }
  
  public int minSize() {
		  return (int)Math.floor(getNum_records()/2);
  }
  
 public Node splitAt(int pos) {
	  
	  int newSize = this.size()-pos;
	  boolean newRoot = newSize>this.num_records;
	  
	  BPLeafNode newNode = new BPLeafNode(comparator, BPLeafNode.num_records, newRoot, this.tree);
	  for(int i=pos; i<this.size(); i++) {
		   newNode.copyRecord(i-pos, this.records[i]);
	  }
	  newNode.rsize = newSize;
	  this.rsize = pos;

	  if(this.isRoot) {
		  this.id = this.tree.getNextNodeId();
		  this.tree.getDisk().storeBlock(this.id.toString());
	  }
	  
	  this.isRoot = false;
	  
	  return newNode;
  }
  
public int getNum_records() {
	return num_records;
}

public Node makeRoot() {
	
	BPLeafNode auxNode = new BPLeafNode(comparator, this.num_records, true, this.tree);
	for(int i=0; i<this.size(); i++) {
		auxNode.append(this.records[i], null);
	}
	this.tree.getDisk().releaseBlock(this.id);
	return auxNode;
}
}